﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BF.IBLL.Dictionary;
using Base.Core.UnityFactory;
using BF.Infrastructure;
using System.Web.UI.HtmlControls;
using BF.Model;

namespace BF.Web.pages.Dictionary.HospitalManagement
{
    public partial class HospitalListTreeTable : BasePage
    {
        Idic_OrganizationBLL iBLL = IOCFactory.GetIOCResolve<Idic_OrganizationBLL>();
        List<dic_Dict> dicOrganizationTypeList = new List<dic_Dict>();
        List<dic_Dict> dicOrganizationLevelList = new List<dic_Dict>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDDL();

                if (GetSessionCurrentUserInfo.dic_Organization != null)
                { hidgKey.Value = GetSessionCurrentUserInfo.dic_Organization.gKey.ToString(); }
                else
                { hidgKey.Value = default(Guid).ToString(); }
                hidIsRoot.Value = "true";
                BindList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
                var model = iBLL.GetModel(new Guid(hidgKey.Value));
                if (model.gHigherKey == null || model.gHigherKey == default(Guid))
                { tishiTD.InnerText = "无上级机构"; }
                else
                {
                    model = iBLL.GetModelByCondition(p => p.gKey == model.gHigherKey);
                    if (model != null)
                    { tishiTD.InnerText = model.sOrganizationName; }
                }
            }
        }

        private void BindDDL()
        {
            System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem
            {
                Value = "",
                Text = "--请选择--"
            };

            //绑定机构类型
            if (dicOrganizationTypeList == null || dicOrganizationTypeList.Count == 0)
                dicOrganizationTypeList = GetDictList("sOrganizationType");
            this.sOrganizationType.DataSource = dicOrganizationTypeList;
            this.sOrganizationType.DataValueField = "sCode";
            this.sOrganizationType.DataTextField = "sName";
            this.sOrganizationType.DataBind();
            this.sOrganizationType.Items.Insert(0, li);

            //绑定机构级别
            if (dicOrganizationLevelList == null || dicOrganizationLevelList.Count == 0)
                dicOrganizationLevelList = GetDictList("sOrganizationLevel").Where(P => P.sCode != "0").OrderBy(P => P.iSort).ToList();
            this.sOrganizationLevel.DataSource = dicOrganizationLevelList;
            this.sOrganizationLevel.DataValueField = "sCode";
            this.sOrganizationLevel.DataTextField = "sName";
            this.sOrganizationLevel.DataBind();
            this.sOrganizationLevel.Items.Insert(0, li);

            //dic_Hospital tempModel = GetSessionCurrentUserInfo.dic_Hospital;
        }

        /// <summary>
        /// 获取机构级别名称
        /// </summary>
        /// <param name="sCode"></param>
        /// <returns></returns>
        protected string GetsOrganizationLevelName(string sCode)
        {
            if (dicOrganizationLevelList == null || dicOrganizationLevelList.Count == 0)
                dicOrganizationLevelList = GetDictList("sOrganizationLevel");
            if (dicOrganizationLevelList.Count == 0)
            { return ""; }
            if (dicOrganizationLevelList.Where(P => P.sCode == sCode).ToList().Count == 0)
            { return ""; }
            return dicOrganizationLevelList.Where(P => P.sCode == sCode).FirstOrDefault().sName;
        }

        /// <summary>
        /// 获取机构类型名称
        /// </summary>
        /// <param name="sCode"></param>
        /// <returns></returns>
        protected string GetsOrganizationTypeName(string sCode)
        {
            var list = GetDictList("sOrganizationType");
            if (list != null && list.Count > 0)
            {
                return list.Where(P => P.sCode == sCode).FirstOrDefault().sName;
            }
            else
            { return ""; }
        }

        /// <summary>
        /// 要求：点击树节点后只查询下一级机构
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        private void BindList(int pageSize, int currentPageIndex)
        {
            string queryFahterKey = hidQueryFahterKey.Value.ToString().Trim();
            Guid queryfatherKeyGuid = default(Guid);
            if (queryFahterKey != "")
            { queryfatherKeyGuid = new Guid(queryFahterKey); }
            //根据隐藏域 处理是否是点击根节点的操作；是 ：只查询根节点下的本机构；否：查询所有下级机构
            if (hidIsRoot.Value == "false")
            {
                AspNetPager1.RecordCount =
            iBLL.GetRowCount(
            P =>
                (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
                //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
                (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
                (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
                (string.IsNullOrEmpty(this.txtOrganizationCode.Text.Trim()) ? true : P.sOrganizationCode == this.txtOrganizationCode.Text.Trim()) &&
                (queryFahterKey == "" ? true : P.gHigherKey == queryfatherKeyGuid)
                );

                var list = iBLL.GetList(
                  P =>
                      (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
                      //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
                      (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
                      (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
                      (string.IsNullOrEmpty(this.txtOrganizationCode.Text.Trim()) ? true : P.sOrganizationCode == this.txtOrganizationCode.Text.Trim()) &&
                      (queryFahterKey == "" ? true : P.gHigherKey == queryfatherKeyGuid)
                       ,
                       P => new { P.sOrganizationType, P.sOrganizationCode },
                       new PageModel(currentPageIndex), true);

                this.Repeater1.DataSource = list;
                this.Repeater1.DataBind();
            }
            else if (hidIsRoot.Value == "true")
            {
                AspNetPager1.RecordCount = iBLL.GetRowCount(

                    P =>

                        (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
                        //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
                        (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
                        (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
                        (string.IsNullOrEmpty(this.txtOrganizationCode.Text.Trim()) ? true : P.sOrganizationCode == this.txtOrganizationCode.Text.Trim()) &&
                        (P.gKey == new Guid(hidgKey.Value))
                        );

                var list = iBLL.GetList(
                  P =>
                      (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
                      //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
                      (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
                      (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
                      (string.IsNullOrEmpty(this.txtOrganizationCode.Text.Trim()) ? true : P.sOrganizationCode == this.txtOrganizationCode.Text.Trim()) &&
                      (P.gKey == new Guid(hidgKey.Value))
                       ,
                       P => new { P.sOrganizationType, P.sOrganizationCode },
                       new PageModel(currentPageIndex), true);

                this.Repeater1.DataSource = list;
                this.Repeater1.DataBind();
            }

        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
        }

        //停用/启用
        protected void lbtnStop_Click(object sender, EventArgs e)
        {
            dic_Organization model = new dic_Organization();
            int count = 0;
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox)Repeater1.Items[i].FindControl("chkID");
                if (cb != null && cb.Checked)
                {
                    model = iBLL.GetModel(Guid.Parse(cb.Value));
                    model.iUse = model.iUse == 0 ? 1 : 0;
                    count++;
                }
            }
            hidMulitStopStart.Value = count.ToString();
            if (iBLL.Update())
            {
                if (model.iUse == 1)
                {
                    Messages("启用成功!");
                    hidFathergKey.Value = model.gHigherKey.ToString();
                    hidSelectedKey.Value = model.gKey.ToString();
                }
                else
                {
                    Messages("停用成功!");
                    hidFathergKey.Value = model.gHigherKey.ToString();
                    hidSelectedKey.Value = model.gHigherKey.ToString();
                }

            }
            else
            {
                if (model.iUse == 1)
                { Messages("启用失败!"); }
                else
                { Messages("停用失败!"); }
            }
            this.AspNetPager1.CurrentPageIndex = 1;
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = 1;
            BindList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
        }

        protected string GetDivisionName(string sCode)
        { return GetAreaNameByAreaCode(sCode); }

        protected void btnExportHospital_Click(object sender, EventArgs e)
        {
            string sdisisionCode = "340100";// areaControl1.SelectedAreaCode;

            if (sdisisionCode.Length == 6)
            {
                if (sdisisionCode.Equals("000000"))
                {
                    sdisisionCode = "";
                }
                else if (sdisisionCode.Substring(2, 4).Equals("0000"))//省级用户
                {
                    sdisisionCode = sdisisionCode.Substring(0, 2);
                }
                else
                {
                    if (sdisisionCode.Substring(4, 2).Equals("00"))//市级用户
                    {
                        sdisisionCode = sdisisionCode.Substring(0, 4);
                    }
                }
            }
            string queryFahterKey = hidQueryFahterKey.Value.ToString().Trim();
            Guid queryfatherKeyGuid = default(Guid);
            if (queryFahterKey != "")
            {
                queryfatherKeyGuid = new Guid(queryFahterKey);
            }
            var list = new List<dic_Organization>();
            //根据隐藏域 处理是否是点击根节点的操作；是 ：只查询根节点下的本机构；否：查询所有下级机构
            if (hidIsRoot.Value == "false")
            {
                list = iBLL.GetList(
           P => (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
               //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
               (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
               (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
                (P.sOrganizationLevel != "0")
               && (queryfatherKeyGuid == default(Guid) ? true : P.gHigherKey == queryfatherKeyGuid)
               ,
           P => new { P.sAreaCode },
           new PageModel(1, int.MaxValue), true);
            }
            else if (hidIsRoot.Value == "true")
            {
                list = iBLL.GetList(
         P =>
             (string.IsNullOrEmpty(this.sOrganizationName.Text.Trim()) ? true : P.sOrganizationName.Contains(this.sOrganizationName.Text.Trim())) &&
             //(string.IsNullOrEmpty(this.sXNHCode.Text.Trim()) ? true : P.sXNHCode.Contains(this.sXNHCode.Text.Trim())) &&
             (string.IsNullOrEmpty(this.sOrganizationType.SelectedValue) ? true : P.sOrganizationType == this.sOrganizationType.SelectedValue) &&
             (string.IsNullOrEmpty(this.sOrganizationLevel.SelectedValue) ? true : P.sOrganizationLevel == this.sOrganizationLevel.SelectedValue) &&
             (P.sOrganizationLevel != "0") &&
             (P.gKey == new Guid(hidgKey.Value)),
             P => new { P.sAreaCode }, new PageModel(1, int.MaxValue), true);
            }

            List<object> exportList = list.Select(h => new
            {
                sOrganizationCode = h.sOrganizationCode,
                sOrganizationName = h.sOrganizationName,
                sOrganizationType = GetsOrganizationTypeName(h.sOrganizationType),
                sOrganizationLevel = GetsOrganizationLevelName(h.sOrganizationLevel),
                sDivisionCode = GetDivisionName(h.sAreaCode),
                sTelephone = h.sTelephone,
                sFax = h.sFax,
                sAddress = h.sAddress,
                sFlag = h.iUse.ToString().Trim() == "1" ? "已启用" : "已停用"
            }).ToList<object>();
            Dictionary<string, string> dect = new Dictionary<string, string>();
            dect.Add("sOrganizationCode", "机构代码");
            dect.Add("sOrganizationName", "机构名称");
            dect.Add("sOrganizationType", "机构类型");
            dect.Add("sOrganizationLevel", "机构级别");
            dect.Add("sDivisionCode", "所属区域");
            dect.Add("sCertificateNo", "执业许可证号");
            dect.Add("sXNHCode", "新农合网点编号");
            dect.Add("sYBCode", "医保网点编号");
            dect.Add("sCharge", "机构负责人");
            dect.Add("sTelephone", "联系电话");
            dect.Add("sFax", "传真");
            dect.Add("sAddress", "通讯地址");
            dect.Add("sLegal", "法人代表");
            dect.Add("sFlag", "有效标识");
            ExExcel<object>(exportList, "医疗机构管理", dect);
        }
    }
}